package cn.qinhao.pethome.login.service.impl;

import cn.qinhao.pethome.basic.base.BaseConstants;
import cn.qinhao.pethome.basic.exception.BusinessException;
import cn.qinhao.pethome.basic.until.MD5Utils;
import cn.qinhao.pethome.basic.until.StrUtils;
import cn.qinhao.pethome.login.domain.EmailRegisterVo;
import cn.qinhao.pethome.login.service.EmailRegisterService;
import cn.qinhao.pethome.org.domain.User;
import cn.qinhao.pethome.org.mapper.UserMapper;
import cn.qinhao.pethome.org.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class EmailRegisterServiceImpl implements EmailRegisterService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
     private IUserService userService;
    @Override
    public void userEmailRegister(EmailRegisterVo emailRegisterVo) {
        //1、校验参数
        //校验邮箱账号是否为空
        if(emailRegisterVo.getEmailNumber()==null){
            throw new BusinessException("邮箱号不能为空");
        }
        //校验输入密码是否为空
        if(emailRegisterVo.getEmailpassword()==null){
            throw new BusinessException("密码不能为空");
        }
        //校验确认密码是否为空
        if(emailRegisterVo.getEmailpasswordRepeat()==null){
            throw new BusinessException("确认密码不能为空");
        }
        //校验输入密码和确认密码是否完全一致
        if(!emailRegisterVo.getEmailpassword().equals(emailRegisterVo.getEmailpasswordRepeat())){
            throw new BusinessException("两次输入密码不一致，请重新输入");
        }
        //2.校验邮箱号是否被注册
        User user1 = userMapper.loadByEmail(emailRegisterVo.getEmailNumber());
        if(user1!=null){
            throw new BusinessException("该邮箱已经被注册，请您去登录");
        }
        //3.校验邮箱格式是否正确
        if(!emailRegisterVo.getEmailNumber().matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*")) {
            throw new BusinessException("请输入正确格式的邮箱");
        }
        //3、保存数据
        User user = new User();
        user.setCreatetime(new Date());
        //密码得加密加盐(使用数字加字母得方式获取)
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(emailRegisterVo.getEmailpassword() + salt);
        user.setSalt(salt);//方便以后用盐值去比对
        user.setPassword(saltPassword);
        user.setUsername(emailRegisterVo.getEmailNumber());
        user.setEmail(emailRegisterVo.getEmailNumber());
        user.setAge(0);//设置默认值，用户自己去改
        user.setState(BaseConstants.User.STATE_NORMAL);
        userService.add(user);
    }
}
